package com.uchiha.nova.core.publisher;

import com.uchiha.nova.core.event.ErrorLogEvent;
import com.uchiha.nova.core.model.LogError;
import com.uchiha.nova.core.tool.util.Exceptions;
import com.uchiha.nova.core.tool.util.Func;
import com.uchiha.nova.core.tool.util.SpringUtil;
import com.uchiha.nova.core.tool.util.WebUtil;

import com.uchiha.nova.core.utils.LogAbstractUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 周林静
 * @Date 2021-10-26 8:49
 * @Version 1.0
 */
@Slf4j
public class ErrorLogPublisher {

    public static void publishEvent(Throwable error, String requestUri) {
        HttpServletRequest request = WebUtil.getRequest();
        LogError logError = new LogError();
        logError.setRequestUri(requestUri);
        if (Func.isNotEmpty(error)) {
            logError.setStackTrace(Exceptions.getStackTraceAsString(error));
            logError.setExceptionName(error.getClass().getName());
            logError.setMessage(error.getMessage());
            StackTraceElement[] elements = error.getStackTrace();
            if (Func.isNotEmpty(elements)) {
                StackTraceElement element = elements[0];
                logError.setMethodName(element.getMethodName());
                logError.setMethodClass(element.getClassName());
                logError.setFileName(element.getFileName());
                logError.setLineNumber(element.getLineNumber());
            }
        }
        LogAbstractUtil.addRequestInfoToLog(request, logError);
        Map<String, Object> event = new HashMap<>(16);
        event.put(EventConstant.EVENT_LOG, logError);
        log.info("ErrorLogPublisher:{}",logError);
        SpringUtil.publishEvent(new ErrorLogEvent(event));
    }

}
